# -*- coding: utf-8 -*- 
"""
@Author: 孟颖
@email: 652044581@qq.com
@date: 2023/4/14 14:16
@desc: O2OA的角色相关
"""
from OAClient import O2OAClient
from config import config
from OAError import O2OAError
from o2oa.OAPerson import O2OAPerson
import requests, json
from o2oa.OAUtils import JsonRemover


class O2OARole(O2OAClient):
    """020A角色相关"""

    def __init__(self):
        super(O2OARole, self).__init__()

    def create(self, role_name, unique="", desc=""):
        """
        @param role_name: 角色名称 经理
        @desc: 创建角色名称
        @return： 返回创建后的资源id
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/role"

        data = {
            "personList": [],
            "groupList": [],
            "identityList": [],
            "unitList": [],
            "description": desc,
            "unique": unique,
            "orderNumber": "",
            "id": "",
            "name": role_name,
            "control": {"allowEdit": True, "allowDelete": True}
        }
        response = requests.post(url=url, headers=self.o2oa_headers, data=json.dumps(data)).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']['id']

    def delete(self, role_id):
        """
        @desc: 删除角色
        @params: role_id 角色的id
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/role/" + role_id
        response = requests.delete(url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']

    def read(self, role_id):
        """
        @desc: 查询单个角色信息
        @params: role_id 角色的id
        @return: role_info 返回角色信息
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/role/" + role_id
        response = requests.get(url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']

    def list(self):
        """
        @desc: 获取角色列表
        @return: 返回角色列表
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/role/list/(0)/next/10"
        response = requests.get(url=url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        count = response['count']

        # 如果比17就不发第二次
        if count <= 10:
            return response['data']

        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/role/list/(0)/next/{}".format(str(count))
        response = requests.get(url=url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        return response['data']


class O2OARoleStaff(O2OAClient):
    """020A角色-人员管理"""

    def __init__(self):
        super(O2OARoleStaff, self).__init__()

    def create(self, role_id, person_id):
        """
        @desc: 给角色添加人员
        @param: role_id: 角色id
        @param: person_id: 人员id
        @return: 
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/role/" + role_id

        response = requests.get(url=url, headers=self.o2oa_headers).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))
        data = response.get("data")

        person_info = O2OAPerson().read(person_id)
        not_need_field = ['woIdentityList', 'woRoleList', 'woGroupList', 'woPersonAttributeList', 'control']
        person_info = JsonRemover(person_info).remove_fields(not_need_field)

        data['personList'].append(person_id)
        data['woPersonList'].append(person_info)

        response = requests.put(url=url, headers=self.o2oa_headers, data=json.dumps(data)).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']

    def delete(self, role_id, person_id):
        """
        @desc: 给角色删除人员
        @param: role_id: 角色id
        @param: person_id: 人员id
        @return:
        """
        url = config.O2OA_URL + "/x_organization_assemble_control/jaxrs/role/" + role_id

        data = {

        }
        response = requests.get(url=url, headers=self.o2oa_headers, data=json.dumps(data)).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        data = response.get("data")

        # 删除操作
        personList = data['personList']
        personList.pop(personList.index(person_id))

        woPersonList = data['woPersonList']
        for i, wo in enumerate(woPersonList):
            if person_id == wo.get('id'):
                woPersonList.pop(i)

        response = requests.put(url=url, headers=self.o2oa_headers, data=json.dumps(data)).json()
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']


if __name__ == '__main__':
    # 创建角色
    # print(O2OARole().create("副经理"))

    # 删除角色
    # print(O2OARole().delete("2029db6d-4d35-4683-916c-22eebdea5679"))

    # 查询角色信息
    print(O2OARole().read('6ddffcb6-a7b1-4b54-8bbc-34c33c041116'))

    # 获取角色列表
    from rich import print_json

    # print_json(json.dumps(O2OARole().list()))

    # 删除所有角色
    # role_list = O2OARole().list()
    # for role in role_list:
    #     id = role['id']
    #     O2OARole().delete(id)

    role_id = '6ddffcb6-a7b1-4b54-8bbc-34c33c041116'
    person_id = 'a21cbff4-51fb-42fc-8510-cac7e8ccf467'
    # 角色增加人员
    # print(O2OARoleStaff().create(role_id, person_id))

    # 角色移除人员
    # print(O2OARoleStaff().delete(role_id, person_id))
